from django.shortcuts import render
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
import hashlib
from common.models import Users

# Create your views here.

def index(request):
    print(request.session["adminuser"])
    return render(request,'admin/index.html')

# 会员登陆页面
def login(request):
    return render(request, 'admin/login.html')

# 执行会员登陆
def dologin(request):
    try:
        # 校验验证码
        verifycode = request.session['verifycode']
        code = request.POST['code']
        if verifycode.lower() != code.lower():
            context = {'info': '验证码错误！'}
        else:
            # 根据用户名获取登陆管理员信息
            uobj=Users.objects.get(username=request.POST["username"])
            if uobj.state==0:
                m=hashlib.md5()
                pwd=request.POST["password"]
                m.update(bytes(pwd,encoding='utf8'))
                # 密码正确，则登陆成功，将登陆信息保存在session,并跳转后台首页
                if uobj.password==m.hexdigest():
                    request.session["adminuser"] = uobj.name
                    return redirect(reverse('myadmin_index'))
                else:
                    context = {"info": "登陆密码错误！"}
            else:
                context = {"info": "该用户不是管理员用户！"}
    except Exception as err:
        context={"info":"登陆失败！"+str(err)}
    return render(request,'admin/login.html',context)

# 退出登陆
def logout(request):
    # 清除本地缓存的登陆信息
    del request.session["adminuser"]
    return redirect(reverse('myadmin_login'))

def verify(request):
    '''验证码'''
    import random
    from PIL import Image,ImageDraw,ImageFont
    # 背景色 宽 高
    bgcolor=(242,164,247)
    width=100
    height=25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    font = ImageFont.truetype('static/msyh.ttf', 21)
    # font = ImageFont.load_default().font
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

